package com.generator;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 代码生成器
 */
public class MpGenerator {

    private static final boolean ISFIRST = false; //是否是第一次生成  因修改了数据库生成只需要生成 xml 和 entity

    private static final String INCLUDE_TABLE = "device_info";
    private static final String logicDeleteFieldName = "";// 逻辑删除字段名称，为空物理删除

    private static final String PACKAGE_NAME = "com.aiobc.community.common.business";

    private static final String PRODUCT_PATH = System.getProperty("user.dir");

    private static final String OUTPUT_ENTITY = PRODUCT_PATH.concat("\\src\\main\\java\\");// 生成java代码的地址

    private static final String ENTITY_PATH = OUTPUT_ENTITY +File.separator+PACKAGE_NAME.replace(".","/") +File.separator + "entity";
    private static final String MAPPER_PATH = OUTPUT_ENTITY +File.separator+PACKAGE_NAME.replace(".","/") +File.separator + "mapper";
    private static final String SERVICE_PATH = OUTPUT_ENTITY +File.separator+PACKAGE_NAME.replace(".","/") +File.separator + "service";
    private static final String SERVICE_IMPL_PATH = OUTPUT_ENTITY +File.separator+PACKAGE_NAME.replace(".","/") +File.separator + "service/impl";
    private static final String CONTROLLER_PATH = OUTPUT_ENTITY +File.separator+PACKAGE_NAME.replace(".","/") +File.separator + "controller";

    private static final String OUTPUT_MAPPERXML = PRODUCT_PATH.concat("\\src\\main\\resources\\mapper\\");//mapper xml所在地址

    private static final String req_package = PACKAGE_NAME +  ".vo.req";
    private static final String resp_package = PACKAGE_NAME +  ".vo.resp";

    private static final String AUTHOR = "zhangzl";

    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/smart_community?characterEncoding=utf-8&useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC";
//    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
//    private static final String USERNAME = "root";
//    private static final String PASSWORD = "123456";
//    private static final String URL = "jdbc:mysql://10.19.13.14:3307/smart_community?characterEncoding=utf-8&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";

    private static final String temp = "/templates/controller.java.ftl";
    private static final String controllerPath = "/custTemplates/controller.java";
    private static final String servicePath = "/custTemplates/service.java";
    private static final String serviceImpPath = "/custTemplates/serviceImpl.java";
    private static final String reqQryTempPath = "/custTemplates/reqQry.java.ftl";
    private static final String reqAddTempPath = "/custTemplates/reqAdd.java.ftl";
    private static final String reqUpdateTempPath = "/custTemplates/reqUpdate.java.ftl";
    private static final String respTempPath =  "/custTemplates/resp.java.ftl";

    private static final String pageRespClass = "Page";
    private static final String pageRespImport = "com.baomidou.mybatisplus.extension.plugins.pagination.Page";
    private static final String respClass = "R";
    private static final String respClassImport = "com.baomidou.mybatisplus.extension.api.R";
    private static final String respSucc = "R.ok";
    private static final String respFail = "R.failed";


    public static void main(String[] args) {
        // 代码生成器
        final AutoGenerator mpg = new AutoGenerator();
        mpg.setGlobalConfig(buildGlobalConfig());
        // 数据源配置
        mpg.setDataSource(buildDataSourceConfig());
        // 包配置
        mpg.setPackageInfo(buildPackageConfig());

        mpg.setCfg(getInjectionConfig());

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        if (!ISFIRST){
            templateConfig.setController(null);
            templateConfig.setService(null);
            templateConfig.setServiceImpl(null);
            templateConfig.setMapper(null);
        }else {
            templateConfig.setController(controllerPath);
            templateConfig.setService(servicePath);
            templateConfig.setServiceImpl(serviceImpPath);
        }
        mpg.setTemplate(templateConfig);
        // 策略配置
        mpg.setStrategy(buildStrategyConfig());
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
    }

    private static InjectionConfig getInjectionConfig(){
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(reqQryTempPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
//                    List<TableField> fields = tableInfo.getFields();
//                    for(int i = 1; i < fields.size(); i++){
//                        TableField f = fields.get(i-1);
//
//                        System.out.println(i + "," + f.getName()+"," + ","+f.getComment());
//                    }
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return OUTPUT_ENTITY +File.separator+req_package.replace(".","/") +File.separator + tableInfo.getEntityName() + "QryReq" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(reqAddTempPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return OUTPUT_ENTITY +File.separator+req_package.replace(".","/") +File.separator + tableInfo.getEntityName() + "AddReq" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(reqUpdateTempPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return OUTPUT_ENTITY +File.separator+req_package.replace(".","/") +File.separator + tableInfo.getEntityName() + "UpdateReq" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(respTempPath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return OUTPUT_ENTITY +File.separator+resp_package.replace(".","/") +File.separator + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String,Object> map = new HashMap<>();
                List<TableInfo> tableInfos = getConfig().getTableInfoList();
                TableInfo tableInfo = tableInfos.get(0);// 一次只能生成一张表的
                String entityName = tableInfo.getEntityName();
                map.put("classname",entityName.substring(0,1).toLowerCase()+ entityName.substring(1));
                map.put("reqPackage",req_package);
                map.put("respPackage",resp_package);
                map.put("respClass",respClass);
                map.put("respClassImport",respClassImport);
                map.put("respSucc",respSucc);
                map.put("respFail",respFail);

                map.put("pageClass",pageRespClass);
                map.put("pageRespImport",pageRespImport);

                setMap(map);
            }
        };

        cfg.setFileOutConfigList(focList);

        return cfg;
    }

    /**
     * 全局构造配置类
     *
     * @return
     * */
    private static GlobalConfig buildGlobalConfig() {
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //设定数据库主键生成策略，会给实体类加TableId注解
        gc.setIdType(IdType.INPUT);
        //项目所在地址
        gc.setOutputDir(OUTPUT_ENTITY);
        //注释作者
        gc.setAuthor(AUTHOR);
        //生成文件不打开
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        //生成result map
        // XML ResultMap
        gc.setBaseResultMap(true);
        //生成java mysql字段映射
        // XML columList
        gc.setBaseColumnList(true);
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        return gc;
    }

    /**
     * 数据库配置信息
     *
     * @return
     * */
    private static DataSourceConfig buildDataSourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        dsc.setTypeConvert(new OracleTypeConvert() {
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //将数据库中timestamp转换成date
                if ( fieldType.toLowerCase().contains( "timestamp" ) || fieldType.toLowerCase().contains( "date" )) {
                    return DbColumnType.DATE;
                }
                //将数据库中timestamp转换成date
                if ( fieldType.toLowerCase().contains( "int" )) {
                    return DbColumnType.INTEGER;
                }
                //将数据库中double转换成Double
                if ( fieldType.toLowerCase().contains( "double" )) {
                    return DbColumnType.DOUBLE;
                }
                if(fieldType.toLowerCase().contains("clob")){
                    return DbColumnType.STRING;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
            }
        });
        return dsc;
    }

    private static PackageConfig buildPackageConfig() {
        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE_NAME);
        pc.setEntity("entity");
        pc.setXml("mapper");
        pc.setController("controller");
        pc.setService("service");
        Map<String,String> map = new HashMap<>();
        if (ISFIRST){
            map.put(ConstVal.MAPPER_PATH, MAPPER_PATH);
            map.put(ConstVal.SERVICE_PATH, SERVICE_PATH);
            map.put(ConstVal.SERVICE_IMPL_PATH, SERVICE_IMPL_PATH);
            map.put(ConstVal.CONTROLLER_PATH, CONTROLLER_PATH);
        }
        map.put(ConstVal.XML_PATH, OUTPUT_MAPPERXML);
        map.put(ConstVal.ENTITY_PATH, ENTITY_PATH);
        pc.setPathInfo(map);
        return pc;
    }

    private static StrategyConfig buildStrategyConfig() {
        StrategyConfig strategy = new StrategyConfig();
        // 命名规则
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        // 默认生成的po类不继承，手动修改继承
        //strategy.setSuperEntityClass((String) null);
        // 实体是否使用Lombok插件
        strategy.setEntityLombokModel(true);
        // 自定义 service 父类
        //strategy.setSuperServiceClass("com.h2t.study.BaseService");
        // 自定义 service 实现类父类
        //strategy.setSuperServiceImplClass("com.h2t.study.BaseServiceImpl");
        // 控制层是否使用Rest风格
        strategy.setRestControllerStyle(true);
//        //去除无效表 -- 可不指定
//        if (!StringUtils.isBlank(EXCLUDE_TABLE)){
//            strategy.setExclude(EXCLUDE_TABLE.split(","));
//        }
        if (!StringUtils.isBlank(INCLUDE_TABLE)){
            //只生成指定表（和上面同时只能选一个）
            strategy.setInclude(INCLUDE_TABLE.split(","));
        }
        if (StringUtils.isNotBlank(logicDeleteFieldName)){
            strategy.setLogicDeleteFieldName(logicDeleteFieldName);// 逻辑删除字段
        }
        return strategy;
    }
}
